import { Radio, Tooltip } from 'antd';
import moment from 'moment';
import React from 'react';
import { FSConfigInfo, FSMonitorGraphInfo, FSMonitorTableInfo } from 'admin/schema/RealTimeMonitor';
import {
  getFSConfigList,
  getFSGraphInfo,
  getFSTableData,
  modifyFSConfig,
} from 'admin/servers/servers';
import '../style.scss';
import { BaseMonitor, BaseMonitorProp } from './BaseComponent';

export class FSMonitor extends BaseMonitor {
  constructor(prop: BaseMonitorProp) {
    super(prop);
    this.title = 'FS Media监控';
    this.btnCaption = '+新增FS';
    this.tickCount = 10;
    this.seriesField = 'fsName';
    this.permissionType = '/systemMonitor/realTimeMonitor/FS';
    this.formConfig = [
      {
        name: 'FS 名称',
        key: 'fsName',
      },
      {
        name: '阈值',
        key: 'fsThreshold',
        verify: (val: string | number) => {
          const verifyNumber = !isNaN(val as number);
          let verifySum = false;
          let verifyFormat = false;
          if (verifyNumber) {
            val > 0 && (verifySum = true);
          }
          !val.toString().startsWith('0') && (verifyFormat = true);
          return verifyNumber && verifySum && verifyFormat;
        },
      },
    ];
    this.state = {
      mode: prop.mode,
    };
  }

  protected getGraphDataReq(): Promise<FSMonitorGraphInfo[]> {
    return new Promise(resolve => {
      const isHistory = this.state.mode === 'history';
      const data = {
        beginTime: isHistory ? this.historyDate : this.realTimeDate,
        endTime: isHistory
          ? moment().format('YYYY-MM-DD') + ' 00:00:00'
          : moment().format('YYYY-MM-DD HH:mm:ss'),
        interval: isHistory ? 30 : void 0,
      };
      getFSGraphInfo(this.currentItemName, data)
        .then(res => {
          resolve(
            res.data.map(item => {
              item.time = isHistory
                ? moment(item.time).format('HH:mm')
                : moment(item.time).format('HH:mm:ss');
              return item;
            })
          );
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }

  protected getTableDataReq(): Promise<FSMonitorTableInfo[]> {
    this.refreshRealTime();
    return new Promise(resolve => {
      const isHistory = this.state.mode === 'history';
      const data = {
        beginTime: isHistory ? this.historyDate : this.realTimeDate,
        endTime: isHistory
          ? moment().format('YYYY-MM-DD') + ' 00:00:00'
          : moment().format('YYYY-MM-DD HH:mm:ss'),
      };
      getFSTableData(data)
        .then(res => {
          resolve(res.data);
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }

  protected getIndicatorsReq(): Promise<FSConfigInfo[]> {
    return new Promise(resolve => {
      getFSConfigList()
        .then(res => {
          resolve(res.data);
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }

  protected modifyIndicatorsReq(params: FSConfigInfo[]): Promise<void> {
    const handledParams = params
      .map(item => {
        return {
          fsName: item.fsName,
          fsThreshold: item.fsThreshold,
        };
      })
      .filter(item => item.fsName && item.fsThreshold);
    return new Promise(resolve => {
      modifyFSConfig(handledParams as FSConfigInfo[])
        .then(res => {
          resolve();
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }

  protected renderTable(): JSX.Element {
    const data = this.tableData as FSMonitorTableInfo[];
    if (!data) {
      return <></>;
    }
    const { currentItemName } = this;
    let realTimeSum = 0;
    let alarmSun = 0;
    data.forEach(item => {
      realTimeSum += item.realTimeCount;
      alarmSun += item.alarmCount;
    });

    return (
      <div className="monitor-fs-table">
        <div className="monitor-fs-tableheader">
          <div className="monitor-fs-tablecol" id="fs-firstcol"></div>
          <div className="monitor-fs-tablecol">最大数</div>
          <div className="monitor-fs-tablecol">最小数</div>
          <div className="monitor-fs-tablecol">平均数</div>
          <div className="monitor-fs-tablecol">实时数</div>
          <div className="monitor-fs-tablecol">阈值</div>
          <div className="monitor-fs-tablecol">告警数</div>
        </div>
        <div className="monitor-fs-tablebody">
          {data.map((item, index) => {
            return (
              <div className={`monitor-fs-row ${!item.onLine && 'offline'}`} key={index}>
                <div className="monitor-fs-tablecol" id="fs-firstcol">
                  <Tooltip title={item.fsName}>
                    <Radio
                      checked={currentItemName === item.fsName}
                      onChange={e => {
                        this.handleCurrentItemNameChange(e, item.fsName);
                      }}
                    />
                    {item.fsName}
                  </Tooltip>
                </div>
                <div className="monitor-fs-tablecol">{item.maxCount}</div>
                <div className="monitor-fs-tablecol">{item.minCount}</div>
                <div className="monitor-fs-tablecol">{item.average}</div>
                <div className="monitor-fs-tablecol">{item.realTimeCount}</div>
                <div className="monitor-fs-tablecol">{item.threshold}</div>
                <div className="monitor-fs-tablecol">{item.alarmCount}</div>
              </div>
            );
          })}
        </div>
        <div className="monitor-fs-tablefooter">
          <div className="monitor-fs-tablecol monitor-table-sum" id="fs-firstcol">
            总计
          </div>
          <div className="monitor-fs-tablecol"></div>
          <div className="monitor-fs-tablecol"></div>
          <div className="monitor-fs-tablecol"></div>
          <div className="monitor-fs-tablecol">{realTimeSum}</div>
          <div className="monitor-fs-tablecol"></div>
          <div className="monitor-fs-tablecol">{alarmSun}</div>
        </div>
      </div>
    );
  }
}
